package com.vector.ding.web.service.bizinfo;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.vector.ding.commons.BizConstant;
import com.vector.ding.commons.util.NumberUtil;
import com.vector.ding.commons.util.StringUtil;
import com.vector.ding.commons.util.collection.CollectionUtil;
import com.vector.ding.commons.util.file.ExcelUtil;
import com.vector.ding.dao.mybatis.mapper.ZmjgBizInfoMapper;
import com.vector.ding.dao.mybatis.model.ZmjgBizInfo;
import com.vector.ding.dao.mybatis.model.ZmjgBizInfoExample;
import com.vector.ding.exception.BaseException;

@Service
public class YzgsBizInfoMgrService {
	
	@Autowired
	private ZmjgBizInfoMapper bizMapper;
	
	public ZmjgBizInfo getBizInfo(String companyName, int belongYear) { 
		if (StringUtil.isEmpty(companyName))
			return null;
		
		ZmjgBizInfoExample example = new ZmjgBizInfoExample();
		example.or().andCompanyNameEqualTo(companyName)
			.andBelongYearEqualTo(belongYear);
		List<ZmjgBizInfo> list = bizMapper.selectByExample(example);
		return CollectionUtil.isEmpty(list) ? null : list.get(0);
	}
	
	public List<ZmjgBizInfo> getBizInfos(String companyName) { 
		if (StringUtil.isEmpty(companyName))
			return Collections.emptyList();
		
		ZmjgBizInfoExample example = new ZmjgBizInfoExample();
		example.or().andCompanyNameEqualTo(companyName);
		List<ZmjgBizInfo> list = bizMapper.selectByExample(example);
		if (CollectionUtil.isEmpty(list))
			return Collections.emptyList();;
		return list;
	}
	
	public List<ZmjgBizInfo> getBizInfo(int pageIndex, int pageSize, 
			HttpServletRequest request) {
		PageHelper.startPage(pageIndex, pageSize, true);
		ZmjgBizInfoExample example = parseBizInfoExample(request);
		//example.setOrderByClause("number asc");
		return bizMapper.selectByExample(example);
	}
	
	private ZmjgBizInfoExample parseBizInfoExample(HttpServletRequest request) {
		ZmjgBizInfoExample example = new ZmjgBizInfoExample();
		String companyName = StringUtil.getString(request.getParameter("company_name"));
		//if (StringUtil.isNotEmpty(companyName))
		example.or().andCompanyNameLike(StringUtil.wrapString(companyName, "%", "%"));
		return example;
	}
	
	public boolean addBizInfo(ZmjgBizInfo record) {
		if (StringUtil.isEmpty(record.getNumber()))
			record.setNumber(UUID.randomUUID().toString());
		return 1 == bizMapper.insertSelective(record);
	}
	
	public boolean updateBizInfo(ZmjgBizInfo record) {
		if (StringUtil.isEmpty(record.getNumber()))
			return false;
		return 1 == bizMapper.updateByPrimaryKeySelective(record);
	}
	
	public void deleteBizInfo(String... nums) {
		if (nums == null)
			return ;
		
		for (String num: nums) {
			bizMapper.deleteByPrimaryKey(num);
		}
	}
	
	public ZmjgBizInfo parseBizInfo(HttpServletRequest request) {
		ZmjgBizInfo record = new ZmjgBizInfo();
		record.setCompanyName(request.getParameter("companyName"));
		record.setBelongYear(NumberUtil.getIntValue(request.getParameter("belongYear")));
		record.setIncom(NumberUtil.getBigDecimal(request.getParameter("incom")));
		record.setIncomGrade(NumberUtil.getBigDecimal(request.getParameter("incomGrade")));
		record.setIncomGrowthRate(NumberUtil.getBigDecimal(request.getParameter("incomGrowthRate")));
		record.setIncomGrowthRateGrade(NumberUtil.getBigDecimal(request.getParameter("incomGrowthRateGrade")));
		
		String profit = request.getParameter("profit");
		String prifitGrade = request.getParameter("prifitGrade");
		String profitGrowthRate = request.getParameter("profitGrowthRate");
		String profitGrowthRateGrade = request.getParameter("profitGrowthRateGrade");
		if(StringUtil.isNotEmpty(profit))
			record.setProfit(NumberUtil.getBigDecimal(profit));
		if(StringUtil.isNotEmpty(profit))
			record.setPrifitGrade(NumberUtil.getBigDecimal(prifitGrade));
		if(StringUtil.isNotEmpty(profitGrowthRate))
			record.setProfitGrowthRate(NumberUtil.getBigDecimal(profitGrowthRate));
		if(StringUtil.isNotEmpty(profitGrowthRateGrade))
			record.setProfitGrowthRateGrade(NumberUtil.getBigDecimal(profitGrowthRateGrade));
		if (StringUtil.isEmpty(request.getParameter("id")))
			record.setId(UUID.randomUUID().toString());
		else
			record.setId(request.getParameter("id"));
		record.setNumber(request.getParameter("number"));
		return record;
	}
	
	public void importFormFile(File importFile) {
		HSSFWorkbook workBook = null;
		int rowIndex = 0;
		try {
			workBook = new HSSFWorkbook(FileUtils.openInputStream(importFile));
			HSSFSheet sheet = workBook.getSheetAt(1);
			HSSFRow titleRow = sheet.getRow(4);
			for (int cellIdx = titleRow.getFirstCellNum(); cellIdx < titleRow.getLastCellNum(); ++cellIdx) {
				System.out.println(titleRow.getCell(cellIdx).toString());
			}
			int rowNum = sheet.getLastRowNum();
			for (rowIndex = 4; rowIndex <= rowNum; ++rowIndex) {
				HSSFRow row = sheet.getRow(rowIndex);
				boolean needImport = checkRowData(row);
				if (!needImport)
					continue;
				
				ZmjgBizInfo bean = getBizInfoBean(row);
				bizMapper.insertSelective(bean);
			}
		} catch (Exception e) {
			e.printStackTrace();
//			throw new BaseException(e);
			throw new BaseException(String.format("第%s行数据格式有误，请检查数据！", rowIndex));
		} finally {
			if (workBook != null) {
				try {
					workBook.close();
				} catch (IOException e) {
					e.printStackTrace();
					throw new BaseException(e);
				}
			}
		}
	}
	
	public ZmjgBizInfo getBizInfoBean(HSSFRow row) {
		ZmjgBizInfo bean = new ZmjgBizInfo();
		bean.setId(UUID.randomUUID().toString());
		bean.setNumber(UUID.randomUUID().toString());
		bean.setCompanyName(ExcelUtil.getStringValue(row.getCell(BizConstant.Yzgs.Biz.COMPANY_NAME_CELL),false));
		bean.setIncom(NumberUtil.getBigDecimal(row.getCell(BizConstant.Yzgs.Biz.INCOM_CELL).getNumericCellValue()));
		bean.setIncomGrade(NumberUtil.getBigDecimal(row.getCell(BizConstant.Yzgs.Biz.INCOM_GRADE_CELL).getNumericCellValue()));
		bean.setIncomGrowthRate(NumberUtil.getBigDecimal(row.getCell(BizConstant.Yzgs.Biz.INCOM_GROWTH_RATE_CELL).getNumericCellValue()));
		bean.setIncomGrowthRateGrade(NumberUtil.getBigDecimal(row.getCell(BizConstant.Yzgs.Biz.INCOM_GROWTH_RATE_GRADE_CELL).getNumericCellValue()));
		bean.setPrifitGrade(NumberUtil.getBigDecimal(row.getCell(BizConstant.Yzgs.Biz.PROFIT_CELL).getNumericCellValue()));
		bean.setPrifitGrade(NumberUtil.getBigDecimal(row.getCell(BizConstant.Yzgs.Biz.PRIFIT_GRADE_CELL).getNumericCellValue()));
		bean.setProfitGrowthRate(NumberUtil.getBigDecimal(row.getCell(BizConstant.Yzgs.Biz.PROFIT_GROWTH_RATE_CELL).getNumericCellValue()));
		bean.setProfitGrowthRateGrade(NumberUtil.getBigDecimal(row.getCell(BizConstant.Yzgs.Biz.profit_growth_rate_grade_CELL).getNumericCellValue()));
		return bean;
	}
	
	private boolean checkRowData(HSSFRow row) {
		String companyName = row.getCell(BizConstant.Yzgs.Biz.COMPANY_NAME_CELL).toString();
		if (StringUtil.isEmpty(companyName))
			return false;
		
		ZmjgBizInfoExample example = new ZmjgBizInfoExample();
		example.or().andNumberEqualTo(companyName);
		return bizMapper.countByExample(example) == 0;
	}

	public BigDecimal getScore(String companyName, Integer belongYear) {
		ZmjgBizInfo bizInfo = getBizInfo(companyName, belongYear);
		if (bizInfo == null)
			return new BigDecimal(0);
		
		BigDecimal score = new BigDecimal(0);
//		BigDecimal incomGrade = bizInfo.getIncomGrade();
//		if (incomGrade != null)
//			score = score.add(incomGrade);
		BigDecimal incomGrowthRateGrade = bizInfo.getIncomGrowthRateGrade();
		if (incomGrowthRateGrade != null)
			score = score.add(incomGrowthRateGrade);
		BigDecimal prifitGrade = bizInfo.getPrifitGrade();
		if (prifitGrade != null)
			score = score.add(prifitGrade);
		BigDecimal profitGrowthRateGrade = bizInfo.getProfitGrowthRateGrade();
		if (profitGrowthRateGrade != null)
			score = score.add(profitGrowthRateGrade);
		
		return score;
	}
	
	public BigDecimal getBaseScore(String companyName, Integer belongYear) {
		ZmjgBizInfo bizInfo = getBizInfo(companyName, belongYear);
		if (bizInfo == null)
			return new BigDecimal(0);
		
		BigDecimal score = new BigDecimal(0);
		BigDecimal incomGrade = bizInfo.getIncomGrade();
		if (incomGrade != null)
			score = score.add(incomGrade);
		
		return score;
	}
	
	public BigDecimal getScore(String companyName) {
		List<ZmjgBizInfo> list = getBizInfos(companyName);
		if (CollectionUtil.isEmpty(list))
			return new BigDecimal(0);
		
		BigDecimal score = new BigDecimal(0);
		for (ZmjgBizInfo bizInfo: list) {
			score = score.add(getScore(bizInfo));
		}
		return score;
	}
	
	public BigDecimal getBaseScore(String companyName) {
		List<ZmjgBizInfo> list = getBizInfos(companyName);
		if (CollectionUtil.isEmpty(list))
			return new BigDecimal(0);
		
		BigDecimal score = new BigDecimal(0);
		for (ZmjgBizInfo bizInfo: list) {
			BigDecimal incomGrade = bizInfo.getIncomGrade();
			if (null != incomGrade)
				score = score.add(incomGrade);
		}
		return score;
	}
	
	
	public BigDecimal getScore(ZmjgBizInfo bizInfo) {
		if (bizInfo == null)
			return new BigDecimal(0);
		
		BigDecimal score = new BigDecimal(0);
//		BigDecimal incomGrade = bizInfo.getIncomGrade();
//		if (incomGrade != null)
//			score = score.add(incomGrade);
		BigDecimal incomGrowthRateGrade = bizInfo.getIncomGrowthRateGrade();
		if (incomGrowthRateGrade != null)
			score = score.add(incomGrowthRateGrade);
		BigDecimal prifitGrade = bizInfo.getPrifitGrade();
		if (prifitGrade != null)
			score = score.add(prifitGrade);
		BigDecimal profitGrowthRateGrade = bizInfo.getProfitGrowthRateGrade();
		if (profitGrowthRateGrade != null)
			score = score.add(profitGrowthRateGrade);
		
		return score;
	}
}
